package cn.opopopo.wordexport.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.opopopo.wordexport.mode.export.ExportFileEnum;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static cn.opopopo.wordexport.mode.export.ExportFileEnum.CIRCULATION;
import static cn.opopopo.wordexport.mode.export.ExportFileEnum.FORM_DATA;
import static cn.opopopo.wordexport.util.DocumentToByteArray.convertXWPFDocumentToByteArray;

@Controller
@RequestMapping("/export")
public class ExportController {

    @GetMapping("/show")
    public String showExportPage(Model model) {
        // 在视图中展示文件选择选项，例如多个复选框或下拉列表
        List<String> fileNames = Arrays.asList("file1.csv", "file2.csv", "file3.csv");
        model.addAttribute("fileNames", fileNames);
        return "exportPage";
    }

    @GetMapping("/generate")
    public void generateExport(HttpServletResponse response) {
        try {
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=exportedFiles.zip");
            ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
            List<String> selectedFiles=CollectionUtil.newArrayList("1","2","4");
            for (String fileName : selectedFiles) {
                XWPFDocument document = new XWPFDocument();
                XWPFParagraph paragraph = document.createParagraph();
                XWPFRun run = paragraph.createRun();
                run.setText("Hello, World!");
                run.setTextHighlightColor("blue");
                XWPFTable table = document.createTable(4,4);
                // 添加表格内容
                table.getRow(0).getCell(0).setText("1");
                table.getRow(0).getCell(1).setText("张三");
                table.getRow(0).getCell(2).setText("李四");
                table.getRow(0).getCell(3).setText("王五");
                table.getRow(1).getCell(0).setText("5");
                table.getRow(1).getCell(1).setText("6");
                table.getRow(1).getCell(2).setText("7");
                table.getRow(1).getCell(3).setText("8");
                table.getRow(2).getCell(0).setText("9");
                table.getRow(2).getCell(1).setText("10");
                table.getRow(2).getCell(2).setText("11");
                table.getRow(2).getCell(3).setText("12");
                table.getRow(3).getCell(0).setText("13");
                table.getRow(3).getCell(1).setText("14");
                table.getRow(3).getCell(2).setText("15");
                table.getRow(3).getCell(3).setText("16");
                // 添加图片
                XWPFParagraph imageParagraph = document.createParagraph();
                XWPFRun imageRun = imageParagraph.createRun();
                ClassPathResource resource = new ClassPathResource("staic/57c6-fxpwyhw5134340.jpg");
                imageRun.addPicture(resource.getStream(), Document.PICTURE_TYPE_JPEG, "57c6-fxpwyhw5134340.jpg", Units.toEMU(200), Units.toEMU(200));
                // 设置中文文件名称
                String childFileName = URLEncoder.encode(DateUtil.format(DateUtil.date(), DatePattern.CHINESE_DATE_TIME_PATTERN), "UTF-8");
                byte[] bytes = convertXWPFDocumentToByteArray(document);
                ZipEntry zipEntry = new ZipEntry(fileName+DateUtil.format(DateUtil.date(), DatePattern.CHINESE_DATE_TIME_PATTERN)+".docx");
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write(bytes);
                zipOutputStream.closeEntry();
            }

            zipOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 示例方法：导出单个CSV文件
    private byte[] exportSingleCSV(String fileName) {
        // 此处为示例，您需要编写实际的CSV导出逻辑
        StringBuilder csvData = new StringBuilder();
        csvData.append("Name, Age, Email\n");
        csvData.append("John, 30, john@example.com\n");
        csvData.append("Alice, 28, alice@example.com\n");

        return csvData.toString().getBytes();
    }



    @GetMapping("/export")
    public void export(HttpServletResponse response, @RequestParam List<ExportFileEnum> exportFileEnums) {

        try {
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=exportedFiles.zip");
            ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());


            ArrayList<ExportFileEnum> exportFileEnums1 = CollectionUtil.newArrayList(CIRCULATION, FORM_DATA);


            for (ExportFileEnum exportFileEnum : exportFileEnums1) {
                ZipEntry zipEntry = new ZipEntry(exportFileEnum.fileName()+exportFileEnum.suffix());
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write(exportFileEnum.data("1"));
                zipOutputStream.closeEntry();
            }

            zipOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}